package com.example.job.controller;

import com.example.job.po.SysJob;
import com.example.job.quartz.SysUserNotifyJob;
import com.example.job.quartz.SysUserTmpJob;
import com.example.job.service.SysJobService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author chentao
 * @version 1.0
 * @description: TODO
 * @date 2025/3/26 下午11:06
 */
@RestController
public class SysJobController {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private SysJobService sysJobService;

    /***
     * 添加临时任务
     * @param name
     * @param minute
     */
    @RequestMapping(value = "addTmpJob")
    public SysJob addTmpJob(@RequestParam(defaultValue = "测试临时任务") String name, @RequestParam(defaultValue = "1") int minute) throws Exception {
        return sysJobService.addJob(name, minute, new SysUserTmpJob(), true, null);
    }

    /***
     * 添加定时任务
     * @param name
     * @param cron
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "addJob")
    public SysJob addJob(@RequestParam(defaultValue = "测试任务") String name, @RequestParam(defaultValue = "*/15 * * * * ?") String cron) throws Exception {
        return sysJobService.addJob(name, cron, new SysUserNotifyJob(), null, true, null);
    }

    /***
     * 动态修改定时任务
     * @param id
     * @param cron
     * @return
     */
    @RequestMapping(value = "updateJob")
    public Long updateJob(@RequestParam(defaultValue = "1") Long id, @RequestParam(defaultValue = "*/20 * * * * ?") String cron) throws Exception {
        SysJob sysJob = sysJobService.getById(id);
        sysJob.setCron(cron);
        sysJobService.updateJob(sysJob);
        return sysJob.getId();
    }

    /***
     * 开始任务
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "startJob")
    public Long startJob(@RequestParam(defaultValue = "1") Long id) throws Exception {
        SysJob sysJob = sysJobService.getById(id);
        sysJob.setStatus(true);
        sysJobService.updateJob(sysJob);
        return sysJob.getId();
    }

    /***
     * 停止任务
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "stopJob")
    public Long stopJob(@RequestParam(defaultValue = "1") Long id) throws Exception {
        SysJob sysJob = sysJobService.getById(id);
        sysJob.setStatus(false);
        sysJobService.updateJob(sysJob);
        return sysJob.getId();
    }
}
